<?php
namespace app\api\controller;

use app\admin\model\exam\UserScoreLogModel;
use app\admin\model\yalimedia\LectureUser;
use app\common\controller\Api;
use app\admin\model\yalimedia\Lecture;
use app\admin\model\yalimedia\LectureAllocation;
use app\common\model\Answer;
use app\common\model\Config;
use app\common\model\Course;
use app\common\model\CourseQuestion;
use app\common\model\Rate;
use app\common\model\ScoreLog;
use app\common\model\User;
use app\common\model\UserGroup;
use app\common\services\AnswerService;
use app\common\services\UrlService;
use think\Db;

/**
 * 消息接口
 */
class Extend extends Api
{
    protected $noNeedLogin = ['myLecture'];
    protected $noNeedRight = ['*'];

    public function myLecture()
    {
        $sql1 = LectureUser::with('lecture')->where('status',1)->where('user_id',$this->auth->id)->buildSql();
        $sql2 = LectureAllocation::with('lecture')->where('status',1)->where('group_id',$this->auth->group_id)->buildSql();
        $sql = Db::table($sql1.' a')->union($sql2,true)->buildSql();
        if($this->request->param('type')){
            $page = $this->request->post('page',0);
            $limit = $this->request->post('limit',10);
            $count = Db::table($sql.' a')->group('lecture__id')->count();
            $data = Db::table($sql.' a')->group('lecture__id')->page($page,$limit)->order("lecture__starttime asc")->select();
            foreach ($data as &$v){
                $v['lecture__cover'] = UrlService::getFileUrl($v['lecture__cover']);
            }
            return $this->success('success',['total'=>$count,'data'=>$data]);
        }else{
            $data = $data = Db::table($sql.' a')->group('lecture__id')->order('lecture__starttime')->limit(3)->select();
            foreach ($data as &$v){
                $v['lecture__cover'] = UrlService::getFileUrl($v['lecture__cover']);
            }
            return $this->success('success',$data);
        }
    }

    public function learning()
    {
        $an = Answer::where('day',date('Y-m-d'))->where('user_id',$this->auth->id)->find();
        if($an){
            Answer::where('day',date('Y-m-d'))->where('user_id',$this->auth->id)->inc('minute')->update(['updatetime'=>time()]);
        }else{
            Answer::insert([
                'user_id'=>$this->auth->id,
                'day'=>date('Y-m-d'),
                'minute'=>1,
                'createtime'=>time(),
                'updatetime'=>time()
            ]);
        }
        if(input('id')){
            AnswerService::setDuration(input('id'),$this->auth->id);
        }
        return $this->success('成功');
    }

    public function ranking()
    {
        $page = input('page',1);
        $limit = input('limit',100);
        $total = User::count();
        $list = collection(User::field('id,username,mobile,avatar,score')->order('score','desc')->page($page,$limit)->select())->toArray();

        foreach ($list as $k=>&$v){
            $v['rank'] = $k + 1;
        }
        return $this->success('success',['total'=>$total,'list'=>$list]);
    }

    public function myranking()
    {

        $data = collection(User::field('id,username,mobile,avatar,score')->order('score','desc')->select())->toArray();
        $ranking = [];
        foreach ($data as $k=>$v){
            if($v['id'] == $this->auth->id){
                $v['ranking'] = $k + 1;
                $ranking = $v;
            }
        }
        return $this->success('success',$ranking);
    }

    public function scoredetil()
    {
        $page = input('page',1);
        $limit = input('limit',10);
        $total = ScoreLog::with('user')->count();
        $data = collection(ScoreLog::with('user')->order('score_log.id','desc')->page($page,$limit)->select())->toArray();

        $list = [];
        foreach ($data as $v){
            $list[] = ['id'=>$v['id'],'score'=>$v['score'],'before'=>$v['before'],'after'=>$v['after'],'memo'=>$v['memo'],'username'=>$v['user']['username'],'avatar'=>$v['user']['avatar'],'createtime'=>date('Y-m-d H:i:s',$v['createtime'])];
        }
        return $this->success('success',['total'=>$total,'list'=>$list]);
    }

    public function explain()
    {
        return $this->success('success',Config::where('name','score_explain')->value('value'));
    }

    public function usercenter()
    {
        
        $count = Answer::where('user_id',$this->auth->id)->count();
        $data  = Answer::where('day',date('Y-d-m'))->where('user_id',$this->auth->id)->find();
        $zero  = strtotime(date('Y-m-d'));
        $now   = time();
        $score = ScoreLog::whereBetween('createtime',"{$zero},{$now}")->where('user_id',$this->auth->id)->count();
        $msg   = \app\common\model\Sysmessage::where('user_id',$this->auth->id)->where('read',0)->count();
        
        $group_name     = '';
        if(isset($this->auth->group_id)){
            $group_name = UserGroup::where('id',$this->auth->group_id)->value('name') ?? '';
        }
        return $this->success('success',['day'=>$count,'score'=>$score,'answernum'=>$data['answernum']??0,'msg'=>$msg,'num_comments'=>$this->auth->num_comments,'group_name'=>$group_name]);
    }

    public function learningdata()
    {
        $date = input('year').'-'.sprintf("%02d", input('month')).'-01 00:00:00';
        $daydata = array_values($this->getMonth(strtotime($date)));
        $daydatas = $daydata;
        $list = [];
        $final = array_pop($daydatas);

        $data = collection(Answer::where('user_id',$this->auth->id)->whereBetween('day',[$daydata[0],$final])->select())->toArray();

        $data = array_column($data,null,'day');

        foreach ($daydata as $v){

            if(input('type')){
                if(isset($data[$v])){
                    $list []= $data[$v]['minute'];
                }else{
                    $list []= 0;
                }
            }else{
                if(isset($data[$v])){
                    $list []= $data[$v]['answernum'];
                }else{
                    $list []= 0;
                }
            }
        }
        foreach ($daydata as &$vs){
            $vs = date('m/d',strtotime($vs));
        }
        return $this->success('success',['list'=>$list,'date'=>$daydata]);
    }

    /**
     * 获取最近七天所有日期
     * @param string $time
     * @param string $format
     * @return array
     */
    function get_weeks($time = '', $format='Y-m-d'){
        $time = $time != '' ? $time : time();
        //组合数据
        $date = [];
        for ($i=1; $i<=7; $i++){
            $date[$i] = date($format ,strtotime( '+' . ($i-7) .' days', $time));
        }
        return $date;
    }

    /**
     * 获取某月所有时间
     * @param string $time 某天时间戳
     * @param string $format 转换的时间格式
     * @return array
     */
    public static function getMonth($time = '', $format='Y-m-d'){
        $time = $time != '' ? $time : time();
        //获取当前周几
        $week = date('d', $time);
        $date = [];
        for ($i=1; $i<= date('t', $time); $i++){
            $date[$i] = date($format ,strtotime( '+' . ($i-$week) .' days', $time));
        }
        return $date;
    }

    public function learningRate()
    {
        $page = input('page',1);
        $limit = input('limit',10);
        $type = input('type',0);
        $count = Rate::where('user_id',$this->auth->id)->count();
        $field = "course_id,duration,rate,total";
        switch ($type){
            case 0:
                $data = collection(Rate::field($field)->where('user_id',$this->auth->id)->order('id','desc')->page($page,$limit)->select())->toArray();
                break;
            case 1:
                $data = collection(Course::alias('a')->join('yalimedia_course_user b','a.id=b.course_id','left')->join('yalimedian_rate c','a.id=c.course_id','left')->field('a.*')->where('a.is_buy = 0 and a.status = 1 and c.id is null')->whereOr('b.id > 0 and c.id is null and a.status=1 and b.user_id='.$this->auth->id)->page($page,$limit)->select())->toArray();
                break;
            case 2:
                $data = collection(Rate::field($field)->where('user_id',$this->auth->id)->where('rate',100)->order('id','desc')->page($page,$limit)->select())->toArray();
                break;
        }

        if($type == 1){
            foreach ($data as &$v){
                $v['cover'] = UrlService::getFileUrl($v['cover']);
                $temp = $v;
                $v = [
                    'course_id'=>$temp['id'],
                    'duration'=>0,
                    'rate'=>0,
                    'total'=>CourseQuestion::where('course_id',$temp['id'])->count()
                ];
                $v['course'] = $temp;
            }
        }else{
            foreach ($data as &$v){
                $course = Course::where('id',$v['course_id'])->find();
                if($course){
                    $course = $course->toArray();

                    $course['cover'] = UrlService::getFileUrl(Course::where('id',$course['id'])->value('cover'));
                }
                $v['course'] = $course;
            }
        }

        return $this->success('success',['total'=>$count,'list'=>$data]);
    }
}